<?php
/**
 * 功能权限模型
 *
 * Author:李强
 * Company:上海煦鸣网络科技有限公司
 * Date:2018-01-03
 */

namespace App\Models;

use App\Traits\ConfigCache;
use Illuminate\Support\Facades\Auth;
use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
    use ConfigCache;
    //
    protected $table = "permissions";
    protected $primaryKey = "id";
    protected $guarded = [];
    public $timestamps = true;


    public static $key = "name";

    public static $cache_key = "admin.permissions";

    /**
     * 获取后台管理顶部菜单
     *
     * @return array
     */
    public static function topmenu()
    {
        $menus = self::admin_menu(0);
        $top_menus = [];
        foreach ($menus as $menu) {
            $top_menus[] = [
                "id" => $menu->id,
                "title" => $menu->display_name,
                "icon" => $menu->icon,
                "pid" => $menu->id,
                "actions" => $menu->actions,
                "href" => $menu->controller != 'sysmenu' ? route($menu->name) : '',
                "children" => []
            ];
        }
        return $top_menus;
    }

    /**
     * 获取某个菜单下的所有子菜单
     *
     * @param $pid
     */
    public static function submenus($pid, $with_self = false, $is_all = false, $level = 1)
    {
        return self::getSubMenus($pid, $with_self, $is_all, $level);
    }

    /**
     * 递归获取菜单
     *
     * @param $pid
     * @param int $Level
     * @return array|bool
     */
    public static function getSubMenus($pid, $with_self = false, $is_all = false, $Level = 1)
    {
        $datas = self::admin_menu($pid, $with_self, $is_all);
        $Level++;
        $ret = [];
        if (count($datas) > 0) {
            foreach ($datas as $data) {
                $id = $data->id;
                $array = [
                    "id" => $data->id,
                    "pid" => $data->pid,
                    "title" => $data->display_name,
                    "icon" => $data->icon,
                    "route_name" => $data->name,
                    'actions' => $data->actions,
                    "is_menu" => $data->is_menu,
                    "href" => $data->is_menu == 1 ? ($data->controller != 'sysmenu' ? route($data->name) : '') : '',
                ];
                $ret[$id] = $array;

                $child = self::getSubMenus($data->id, $with_self, $is_all, $Level);
                //由于后台管理界面只支持三层，超出的不层级的不显示
                if ($child && $Level <= 4) {
                    $ret[$id]['children'] = $child;
                }
            }
            return $ret;
        }
        return false;
    }

    /**
     * 按父ID查找菜单子项
     *
     * @param $parentid 父菜单ID
     * @param bool $with_self 是否包括他自己
     * @return array
     */
    public static function admin_menu($parentid, $with_self = false, $is_all = false)
    {
        //父节点ID
        $parentid = (int)$parentid;
        $result = self::where(['pid' => $parentid, 'status' => 1])->orderBy('sort', 'asc')->get();
        if ($with_self && $parentid > 0) {
            $result2[] = self::where(['id' => $parentid])->first();
            $result = $result->merge($result2);
        }
        //管理员权限全部功能均能操作
        if ($is_all || Role::isAdmin()) {
            return $result;
        }

        $array = array();
        if (count($result)) {
            foreach ($result as $v) {
                if (Auth::user()->hasPermission($v)) {
                    $array[] = $v;
                }
            }
        }
        return $array;
    }

    /**
     * 根据权限ID以此获取父级
     *
     * @param $id
     * @param array $result
     * @return array
     */
    public static function getParents($id, $result = [])
    {
        $permission = self::find($id);
        if (!is_null($permission)) {
            $result[] = $id;
            return self::getParents($permission->pid, $result);
        } else {
            $result[] = $id;
        }
        return $result;
    }

    /**
     * 获取子分类
     *
     * @param $id
     * @param array $result
     * @return mixed
     */
    public static function getChildren($id, $result = [])
    {
        $children = self::where('pid', $id)->select('id', 'display_name')->get();
        if (!is_null($children)) {
            $result[$id] = $children->toArray();
            foreach ($children as $child) {
                $result = self::getChildren($child->id, $result);
            }
        } else {
            return $result;
        }
        return $result;
    }

    /**
     * 检查是否存在某个菜单项
     *
     * @param $name
     * @param int $id
     * @return bool
     */
    public static function hasName($name, $id = 0)
    {
        if ($name != 'sysmenu.default') {
            $permission = self::where('name', $name)->when($id, function ($query) use ($id) {
                $query->where('id', '!=', $id);
            })->first();
            return !is_null($permission) ? true : false;
        }
        return false;
    }

    /**
     *
     */
    /**
     * 判断某个ID是否在某ID的子级里
     *
     * @param $pid
     * @param $id
     * @return bool
     */
    public static function isInChild($pid, $id)
    {
        $children = self::getChildren($pid);
        $keys = array_keys($children);
        if (in_array($id, $keys)) {
            return true;
        }
        return false;
    }
}
